package com.irdstudio.efp.riskm.service.impl;

import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.esb.service.bo.req.basicfn.MonReliefDatasAppReqBean;
import com.irdstudio.efp.esb.service.bo.resp.basicfn.MonReliefDatasAppRespBean;
import com.irdstudio.efp.esb.service.facade.basicfn.MonReliefDatasAppService;
import com.irdstudio.efp.flow.common.vo.PageApproveVO;
import com.irdstudio.efp.riskm.common.RiskColltConstant;
import com.irdstudio.efp.riskm.common.RiskcataConstant;
import com.irdstudio.efp.riskm.service.dao.MonReliefAppDao;
import com.irdstudio.efp.riskm.service.domain.MonReliefApp;
import com.irdstudio.efp.riskm.service.facade.MonReliefAppApprService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 息费减免审批处理类
 * <p>
 * 需求编号【2019D0509】
 *
 * @author qiuyf
 * @version 0.1 初始为0.1,后续变更则修改
 * @since 2019/11/4 14:47
 */
@Service("flowMonReliefAppService")
public class MonReliefAppApprServiceImpl implements MonReliefAppApprService {

    private static Logger logger = LoggerFactory.getLogger(MonReliefAppApprServiceImpl.class);

    @Autowired
    private MonReliefAppDao monReliefAppDao;

    @Autowired
    @Qualifier("monReliefDatasAppService")
    private MonReliefDatasAppService monReliefDatasAppService;


    @Autowired
    private MonReliefAppPassLoanSynImpl monReliefAppPassLoanSyn;

    @Override
    public void pass(String bizSerno, PageApproveVO pageApproveVo) {
        logger.debug("======>息费减免申请审批通过逻辑后处理开始，息费减免申请流水号为：" + bizSerno + "<======");
        try {
            MonReliefApp monReliefApp = getMonReliefAppByPk(bizSerno);
            setInfoToMonReliefApp(monReliefApp, pageApproveVo, ConsoleConstant.APRV_STATUS_03);
            if(monReliefAppDao.updateByPk(monReliefApp) != 1){
                throw new Exception("息费减免申请审批通过后，更新审批信息失败！");
            }

            try {
                //调用互金贷款豁免接口
                MonReliefDatasAppRespBean respBean = monReliefDatasAppService.applyMonReliefDatasApp(createReqBean(monReliefApp));
                if (Objects.nonNull(respBean)) {
                    //更新息费减免状态
                    if(updReliefStatus(monReliefApp, RiskColltConstant.RELIEF_STS_03) != 1){
                        //优化 TODO 可能需要发告警
                        logger.error("息费减免申请审批通过，调用互金贷款豁免接口成功后，更新息费减免状态失败！");
                    }
                }else{
                    updReliefStatus(monReliefApp, RiskColltConstant.RELIEF_STS_04);
                }
            } catch (Exception e){
                monReliefApp.setAprvComment("调用互金贷款豁免接口失败！");
                monReliefApp.setApproveStatus(ConsoleConstant.APRV_STATUS_05);
                updReliefStatus(monReliefApp, RiskColltConstant.RELIEF_STS_04);
                throw e;
            }

            //同步减免后的借据信息、还款计划信息 (优化 TODO 可能需要发告警)
            monReliefAppPassLoanSyn.synLoansFromIFP(monReliefApp);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("======>息费减免申请审批通过逻辑后处理失败，原因:" + e.getMessage());
        }
        logger.debug("======>息费减免申请审批通过逻辑后处理结束，息费减免申请流水号为：" + bizSerno + "<======");
    }

    @Override
    public void refuse(String bizSerno, PageApproveVO pageApproveVo) {
        logger.debug("======>息费减免申请审批拒绝逻辑后处理开始，息费减免申请流水号为：" + bizSerno + "<======");
        try {
            updMonReliefApp(bizSerno, pageApproveVo, ConsoleConstant.APRV_STATUS_04);
            updReliefStatus(bizSerno, RiskColltConstant.RELIEF_STS_05);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.debug("======>息费减免申请审批拒绝逻辑后处理结束，息费减免申请流水号为：" + bizSerno + "<======");
    }

    @Override
    public void repulse(String bizSerno, PageApproveVO pageApproveVo) {
        logger.debug("======>息费减免申请审批打回逻辑后处理开始，息费减免申请流水号为：" + bizSerno + "<======");
        try {
            updMonReliefApp(bizSerno, pageApproveVo, ConsoleConstant.APRV_STATUS_05);
            updReliefStatus(bizSerno, RiskColltConstant.RELIEF_STS_01);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.debug("======>息费减免申请审批打回逻辑后处理结束，息费减免申请流水号为：" + bizSerno + "<======");
    }

    /**
     * 更新息费减免申请信息
     * @param bizSerno
     * @param pageApproveVo
     * @param apprStatus
     * @throws Exception
     */
    private void updMonReliefApp(String bizSerno, PageApproveVO pageApproveVo, String apprStatus) throws Exception {
        MonReliefApp monReliefApp = getMonReliefAppByPk(bizSerno);
        setInfoToMonReliefApp(monReliefApp, pageApproveVo, apprStatus);
        monReliefAppDao.updateByPk(monReliefApp);
    }

    /**
     * 设置息费减免审批信息
     * @param monReliefApp
     * @param pageApproveVo
     * @param apprStatus
     */
    private static void setInfoToMonReliefApp(MonReliefApp monReliefApp, PageApproveVO pageApproveVo, String apprStatus){
        monReliefApp.setApproveStatus(apprStatus);
        monReliefApp.setAprvUserCode(pageApproveVo.getAprvUserId());
        monReliefApp.setAprvComment(pageApproveVo.getAprvComment());
        monReliefApp.setAprvTime(TimeUtil.getCurrentDateTime());
        monReliefApp.setLastChgUsr(pageApproveVo.getAprvUserId());
    }

    /**
     * 获取息费减免申请信息
     * @param bizSerno
     * @return
     * @throws Exception
     */
    private MonReliefApp getMonReliefAppByPk(String bizSerno) throws Exception {
        MonReliefApp monReliefApp = new MonReliefApp();
        monReliefApp.setReliefAppNo(bizSerno);
        monReliefApp = monReliefAppDao.queryByPk(monReliefApp);
        if (Objects.isNull(monReliefApp)) {
            throw new Exception("根据息费减免申请流水号:" + bizSerno + ",获取到的息费减免申请信息为空！");
        }
        return monReliefApp;
    }

    /**
     * 组装贷款豁免接口请求报文
     * @param monReliefApp
     * @return
     */
    private MonReliefDatasAppReqBean createReqBean(MonReliefApp monReliefApp) {
        MonReliefDatasAppReqBean reqBean = new MonReliefDatasAppReqBean();
        //贷款号
        reqBean.setAcctNo(monReliefApp.getLoanSeq());
        //发放号
        reqBean.setAcctNoSrlNo(monReliefApp.getDistrNo());
        //豁免日期 N
        //还款类型  固定值：WV-豁免
        reqBean.setRpymtTp("WV");
        //豁免金额，仅可以豁免利息、罚息和复利
        reqBean.setRcylAmt(monReliefApp.getReliefLmt().doubleValue());
        //豁免原因 固定值：201-贷款回收
        reqBean.setAcctUsg("201");
        //豁免备注
        return reqBean;
    }

    /**
     * 更新息费减免状态
     * @param monReliefApp
     * @param reliefStatus
     * @return
     */
    private int updReliefStatus(MonReliefApp monReliefApp, String reliefStatus){
        monReliefApp.setReliefStatus(reliefStatus);
        return monReliefAppDao.updateByPk(monReliefApp);
    }

    /**
     * 更新息费减免状态
     * @param bizSerno
     * @param reliefStatus
     */
    private void updReliefStatus(String bizSerno, String reliefStatus){
        MonReliefApp monReliefApp = new MonReliefApp();
        monReliefApp.setReliefAppNo(bizSerno);
        monReliefApp.setReliefStatus(reliefStatus);
        if(monReliefAppDao.updateByPk(monReliefApp) != 1){
            logger.error("通过息费减免申请流水号：" + bizSerno + "更新息费减免申请信息失败！");
        }
    }

}
